<template>
  <div class="page_container">
    <PageTitle />

    <div class="search_part">
      <div class="left">
        <div class="item">
          <span>权限名称：</span>
          <el-input v-model="permissionTitle" placeholder="请输入权限名称" clearable></el-input>
          <el-button @click="searchPermission" type="primary" round>
            搜索
          </el-button>
        </div>
      </div>
      <div class="right">
        <el-button
          v-if="isBtnPermission('PermissionAdd')"
          @click="$router.push({name:'PermissionAdd'})"
          type="primary"
          round
        >
          新增
        </el-button>
      </div>
    </div>
    <TableScroll
      :data="permissionList"
      ref="tableScroll"
      :options="{
        rowKey: 'id',
        load: loadNode,
        rowClassName: rowClassName,
        lazy: true
      }"
      style="margin-bottom:20px"
      bottom="0"
    >
      <el-table-column prop="title" show-overflow-tooltip>
        <template slot="header" slot-scope="{}">
          <div style="text-align:center">
            权限名称
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="排序"
        prop="sort"
        align="center"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        label="类型"
        prop="type"
        align="center"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column label="标识" prop="name" align="center" show-overflow-tooltip />
      <el-table-column label="路径" prop="redirect" align="center" show-overflow-tooltip />
      <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip />
      <el-table-column label="状态" align="center" width="80">
        <template slot-scope="{row}">
          <el-switch
            :active-value="1"
            :inactive-value="2"
            v-model="row.state.id"
            @change="changeState(row)"
            :disabled="!isBtnPermission('PermissionState')"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        :width="tableActionWidth(actionBtns)"
        fixed="right"
        v-if="tableActionWidth(actionBtns)"
        :key="actionRefreshKey"
      >
        <template slot-scope="{row}">
          <el-button
            v-if="isBtnPermission('PermissionDetail')"
            @click="$router.push({name:'PermissionDetail', params: {id: row.id}})"
            type="success"
            round
          >
            查看
          </el-button>
          <el-button
            v-if="isBtnPermission('PermissionEdit')"
            @click="$router.push({name:'PermissionEdit', params: {id: row.id}})"
            type="warning"
            round
          >
            修改
          </el-button>
          <el-button
            v-if="isBtnPermission('PermissionDelete')"
            @click="del(row)"
            type="danger"
            round
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </TableScroll>
  </div>
</template>

<script>
import {
  getPermissionList,
  editPermissionState,
  deletePermission
} from '@/api/home/system/permission.js';
import { handlePermissonChange } from '@u/user.js';
import { isDynamicPermission } from '@/setting.js';

export default {
  name: 'Permission',
  data() {
    return {
      actionRefreshKey: '',
      actionBtns: ['PermissionDetail', 'PermissionEdit', 'PermissionDelete'],
      permissionTitle: '',
      permissionList: [],
      maps: new Map()
    };
  },
  async created() {
    this.permissionList = await this.getTreeData();
    const parentId = this.$store.getters.pages.Permission;
    if (parentId) {
      const list = parentId.split(',');
      let i = 0;
      this.$nextTick(() => {
        this.$refs.tableScroll.$el.querySelector('.row_' + list[i]).querySelector('.el-table__expand-icon').click();
        const timer = setInterval(() => {
          i++;
          if (i == list.length) {
            clearInterval(timer);
            return;
          }
          this.$refs.tableScroll.$el.querySelector('.row_' + list[i]).querySelector('.el-table__expand-icon').click();
        }, 500);
      });
      this.$store.commit('layout/removePages', 'Permission');
    }
  },
  methods: {
    rowClassName({ row }) {
      return 'row_' + row.id;
    },
    async getTreeData({ fId = 0, name = '' } = {}) {
      let list = [];
      await getPermissionList({
        params: {
          fId,
          name
        }
      }).then(res => {
        if (res.code == 200) {
          list = res.data;
        }
      });
      return list;
    },
    changeState(row) {
      editPermissionState(row.id, {
        data: {
          stateId: row.state.id
        }
      }).then(async res => {
        if (res.code == 200) {
          if (isDynamicPermission) {
            await handlePermissonChange(this);
          }
          if (this.actionBtns.includes(row.name)) {
            this.actionRefreshKey = new Date().getTime().toString();
          }
        } else {
          row.state.id = row.state.id == 1 ? 2 : 1;
        }
      });
    },
    // 根据权限名称搜索权限
    async searchPermission() {
      this.permissionList = await this.getTreeData({ name: this.permissionTitle });
    },
    // 树形表格懒加载
    async loadNode(tree, treeNode, resolve) {
      this.maps.set(tree.id, { tree, treeNode, resolve }); // 将当前选中节点数据存储到maps中
      const list = await this.getTreeData({ fId: tree.id });
      resolve(list);
    },
    del(row) {
      this.$confirm('确定删除该权限吗？', '删除确认', {
        type: 'warning'
      }).then(() => {
        deletePermission(row.id).then(res => {
          if (res.code == 200) {
            if (isDynamicPermission) {
              handlePermissonChange(this);
            }
            if (row.parentId) {
              const { tree, treeNode, resolve } = this.maps.get(row.parentId); // 根据 parentId 取出对应的节点数据
              this.$set(this.$refs.tableScroll.$children[0].store.states.lazyTreeNodeMap, row.parentId, []); // 将对应节点下的数据清空，从而实现数据的重新加载
              this.loadNode(tree, treeNode, resolve);
            } else {
              const i = this.permissionList.findIndex(item => item.id == row.id);
              if (i != -1) {
                this.permissionList.splice(i, 1);
              }
            }
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
